package com.wu.common.util

import android.content.Context
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableString
import android.text.TextPaint
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.Gravity
import android.view.View
import android.widget.TextView
import com.wu.common.R
import com.zrq.spanbuilder.Spans
import java.util.regex.Pattern

/**
 * 描述:
 *
 * @author zhangrq
 * 2016/11/1 15:56
 */
object TextViewUtils {
    /**
     * 正则表达式：验证手机号
     */
    private const val REGEX_MOBILE = "1\\d{10}"

    fun setText(textView: TextView?, vararg text: CharSequence?) {
        if (textView == null || text.isEmpty())
            return
        val stringBuilder = StringBuilder()
        for (charSequence in text) {

        }
        for (charSequence in text) {
            stringBuilder.append(if (charSequence == null || charSequence.isEmpty()) " " else charSequence)
        }
        textView.text = stringBuilder
    }

    fun setTextHasValue(textView: TextView?, vararg text: CharSequence?) {
        if (textView == null || text.isEmpty())
            return
        val stringBuilder = StringBuilder()
        for (charSequence in text) {
            stringBuilder.append(if (charSequence == null || charSequence.isEmpty()) "- -" else charSequence)
        }
        textView.text = stringBuilder
    }

    /**
     * @param context 上下文
     * @param resId   资源id
     * @param gravity 图片位置
     */
    fun setImageResources(context: Context, resId: Int, gravity: Int, textView: TextView) {
        val drawable = context.resources.getDrawable(resId)
        drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
        val compoundDrawables = textView.compoundDrawables
        when (gravity) {
            Gravity.LEFT// 左
            -> textView.setCompoundDrawables(
                drawable,
                compoundDrawables[1],
                compoundDrawables[2],
                compoundDrawables[3]
            )
            Gravity.TOP// 上
            -> textView.setCompoundDrawables(
                compoundDrawables[0],
                drawable,
                compoundDrawables[2],
                compoundDrawables[3]
            )
            Gravity.RIGHT// 右
            -> textView.setCompoundDrawables(
                compoundDrawables[0],
                compoundDrawables[1],
                drawable,
                compoundDrawables[3]
            )
            Gravity.BOTTOM// 下
            -> textView.setCompoundDrawables(
                compoundDrawables[0],
                compoundDrawables[1],
                compoundDrawables[2],
                drawable
            )
        }

    }

    /**
     * 设置值，并手机号设置高亮
     */
    fun setTextAndCheckPhoneHighLight(
        textView: TextView,
        rawContent: String,
        listener: OnPhoneClickListener
    ) {
        if (TextUtils.isEmpty(rawContent)) {
            return
        }
        // 加载文章内容高亮多个关键字，只高亮一个关键字去掉循环
        val spannableString = SpannableString(rawContent)
        val p = Pattern.compile(REGEX_MOBILE)
        val m = p.matcher(spannableString)
        while (m.find()) {
            val start = m.start()
            val end = m.end()
            spannableString.setSpan(
                PhoneClickableSpan(rawContent.substring(start, end), listener),
                start,
                end,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
        textView.text = spannableString
        textView.movementMethod = LinkMovementMethod.getInstance()
        textView.highlightColor = Color.TRANSPARENT
    }

    /**
     * 设置价格
     */
    @JvmStatic
    @JvmOverloads
    fun setTextViewPrice(
        textView: TextView,
        price: String?,
        unitSize: Int = 13,
        dotBeforePriceSize: Int = 17,
        dotAfterPriceSize: Int = 13,
        unit: String = "¥ ",
        unitBeforeText: String = ""
    ) {
        if (TextUtils.isEmpty(price)) {
            textView.text = ""
            return
        }
        val saveTwoDecimalPrice = StringUtil.saveTwoDecimal(price!!)
        val split = saveTwoDecimalPrice.split(".")
        textView.text = Spans.builder().apply {
            if (!TextUtils.isEmpty(unitBeforeText))
                text(unitBeforeText)
        }.size(unitSize).text(if (split.isNotEmpty()) split[0] else "0")
            .size(dotBeforePriceSize).text(".").text(if (split.size > 1) split[1] else "00")
            .size(dotAfterPriceSize).build()
    }



    @JvmStatic
    @JvmOverloads
    fun setTextViewIntegral(
        textView: TextView,
        price: String?,
        unitSize: Int = 13,
        beforePriceSize: Int = 17,
        afterPriceSize: Int = 13,
        unit: String = "¥ ",
        unitBeforeText: String = "",
        unitAfterText: String = ""
    ) {
        if (TextUtils.isEmpty(price)) {
            textView.text = ""
            return
        }
//        val saveTwoDecimalPrice = StringUtil.saveTwoDecimal(price!!)
//        val split = saveTwoDecimalPrice.split(".")
        textView.text = Spans.builder().apply {
            if (!TextUtils.isEmpty(unitBeforeText))
                text(unitBeforeText).size(beforePriceSize)
        }.text(unit).size(unitSize).text(price)
            .size(beforePriceSize).text(unitAfterText).size(afterPriceSize).color(R.color.black).build()
    }

    class PhoneClickableSpan(
        private val phoneNum: String,
        private val listener: OnPhoneClickListener?
    ) : ClickableSpan() {

        override fun onClick(widget: View) {
            listener?.onPhoneClick(phoneNum)
        }

        override fun updateDrawState(ds: TextPaint) {
            ds.color = Color.parseColor("#4A90E2")
            ds.isUnderlineText = false
        }
    }

    interface OnPhoneClickListener {
        fun onPhoneClick(phoneNum: String)
    }
}
